What is enhanced-resolve?
The enhanced-resolve package is a highly configurable module resolution library for Node.js, which is used by webpack under the hood. It resolves a path to a file or directory in a file system. It can handle complex resolution patterns like module aliases, extensions, and directories with package.json files.
What are enhanced-resolve's main functionalities?
File Resolution
Resolves the path to a file, taking into account file extensions and processing according to the configuration provided.
const { ResolverFactory } = require('enhanced-resolve');
const resolver = ResolverFactory.createResolver({
fileSystem: require('fs'),
extensions: ['.js', '.json']
});
resolver.resolve({}, __dirname, './path/to/file', (err, result) => {
if (err) console.error(err);
else console.log(result);
});
Directory Resolution
Resolves the path to a directory, looking for the 'main' field in the package.json or index.js within that directory.
const { ResolverFactory } = require('enhanced-resolve');
const resolver = ResolverFactory.createResolver({
fileSystem: require('fs'),
mainFields: ['main']
});
resolver.resolve({}, __dirname, './path/to/directory', (err, result) => {
if (err) console.error(err);
else console.log(result);
});
Plugin System
Allows the use of plugins to extend or modify the resolution behavior, providing a high degree of customization.
const { ResolverFactory } = require('enhanced-resolve');
const MyPlugin = require('./MyPlugin');
const resolver = ResolverFactory.createResolver({
fileSystem: require('fs'),
plugins: [new MyPlugin()] // Custom plugin to modify resolution behavior
});
// Use the resolver as before
Other packages similar to enhanced-resolve
resolve
A simple module resolution package that can be used to resolve file paths similarly to Node's 'require.resolve'. It is less configurable than enhanced-resolve but is easier to use for simple resolution tasks.
browser-resolve
A browser-focused module resolver that aims to replicate Node's 'require.resolve' behavior for browser environments. It is similar to enhanced-resolve but with a focus on resolving modules for bundling in the browser.
require-resolve
This package provides a function to resolve a module path relative to a given path. It is a simpler alternative to enhanced-resolve, focusing on resolving require paths without the extensive configuration options.
enhanced-resolve
Offers an async require.resolve function. It's highly configurable.
Features
- plugin system
- provide a custom filesystem
- sync and async node.js filesystems included
Getting Started
Install
npm install enhanced-resolve
yarn add enhanced-resolve
Creating a Resolver
The easiest way to create a resolver is to use the createResolver
function on ResolveFactory
, along with one of the supplied File System implementations.
const {
NodeJsInputFileSystem,
CachedInputFileSystem,
ResolverFactory
} = require('enhanced-resolve');
const myResolver = ResolverFactory.createResolver({
fileSystem: new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000),
extensions: ['.js', '.json']
});
const context = {};
const resolveContext = {};
const lookupStartPath = '/Users/webpack/some/root/dir';
const request = './path/to-look-up.js';
myResolver.resolve({}, lookupStartPath, request, resolveContext, (err, filepath) => {
});
For more examples creating different types resolvers (sync/async, context, etc) see lib/node.js
.
Resolver Options
Field | Default | Description |
---|
alias | [] | A list of module alias configurations or an object which maps key to value |
aliasFields | [] | A list of alias fields in description files |
cacheWithContext | true | If unsafe cache is enabled, includes request.context in the cache key |
descriptionFiles | ["package.json"] | A list of description files to read from |
enforceExtension | false | Enforce that a extension from extensions must be used |
enforceModuleExtension | false | Enforce that a extension from moduleExtensions must be used |
extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files |
mainFields | ["main"] | A list of main fields in description files |
mainFiles | ["index"] | A list of main files in directories |
modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name |
roots | [] | A list of directories to resolve request starting with / from |
ignoreRootsErrors | false | Ignore fatal errors happening during handling of roots (allows to add roots without a breaking change) |
preferAbsolute | false | Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots |
unsafeCache | false | Use this cache object to unsafely cache the successful requests |
plugins | [] | A list of additional resolve plugins which should be applied |
symlinks | true | Whether to resolve symlinks to their symlinked location |
cachePredicate | function() { return true }; | A function which decides whether a request should be cached or not. An object is passed to the function with path and request properties. |
moduleExtensions | [] | A list of module extensions which should be tried for modules |
resolveToContext | false | Resolve to a context instead of a file |
restrictions | [] | A list of resolve restrictions |
fileSystem | | The file system which should be used |
resolver | undefined | A prepared Resolver to which the plugins are attached |
Plugins
Similar to webpack
, the core of enhanced-resolve
functionality is implemented as individual plugins that are executed using Tapable
. These plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved.
A plugin should be a class
(or its ES5 equivalent) with an apply
method. The apply
method will receive a resolver
instance, that can be used to hook in to the event system.
Plugin Boilerplate
class MyResolverPlugin {
constructor(source, target) {
this.source = source;
this.target = target;
}
apply(resolver) {
const target = resolver.ensureHook(this.target);
resolver.getHook(this.source).tapAsync("MyResolverPlugin", (request, resolveContext, callback) => {
resolver.doResolve(target, request, null, resolveContext, callback);
});
}
}
Plugins are executed in a pipeline, and register which event they should be executed before/after. In the example above, source
is the name of the event that starts the pipeline, and target
is what event this plugin should fire, which is what continues the execution of the pipeline. For an example of how these different plugin events create a chain, see lib/ResolverFactory.js
, in the //// pipeline ////
section.
Tests
npm test
Passing options from webpack
If you are using webpack
, and you want to pass custom options to enhanced-resolve
, the options are passed from the resolve
key of your webpack configuration e.g.:
resolve: {
extensions: ['', '.js', '.jsx'],
modules: ['src', 'node_modules'],
plugins: [new DirectoryNamedWebpackPlugin()]
...
},
License
Copyright (c) 2012-2016 Tobias Koppers
MIT (http://www.opensource.org/licenses/mit-license.php)